package com.ihd.ihardware.view.tzc.main.model;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;
import com.ihd.ihardware.api.HttpClient;
import com.ihd.ihardware.app.MyApplication;
import com.ihd.ihardware.common.AppConstans;
import com.ihd.ihardware.pojo.DeviceListRes;
import com.ihd.ihardware.pojo.EmptyRes;
import com.ihd.ihardware.pojo.MembersRes;
import com.ihd.ihardware.pojo.ReportRes;
import com.ihd.ihardware.pojo.UpdateRes;
import com.ihd.ihardware.pojo.UserInfoRes;
import com.ihd.ihardware.pojo.WeightRes;
import com.ihd.ihardware.pojo.WeightTrendsRes;
import com.jeremyliao.liveeventbus.LiveEventBus;

import org.reactivestreams.Publisher;

import java.util.List;

import cn.wowjoy.commonlibrary.http.BaseSubscriber;
import cn.wowjoy.commonlibrary.utils.FileUtils;
import cn.wowjoy.commonlibrary.utils.RxSchedulerTransformer;
import cn.wowjoy.commonlibrary.utils.SPUtils;
import cn.wowjoy.commonlibrary.viewmodel.BaseRepository;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Function;
import io.reactivex.observers.DisposableObserver;
import io.reactivex.schedulers.Schedulers;
import io.reactivex.subscribers.DisposableSubscriber;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;

public class BalanceRepository extends BaseRepository {

    public void report(String familyId) {
        addDisposable(HttpClient.getService().report(familyId == null ? "" : familyId)
                .compose(new RxSchedulerTransformer<>())
                .subscribeWith(new BaseSubscriber<ReportRes>(AppConstans.HANDREPORT) {
                }));
    }

    public void getWeight(String familyId) {
        addDisposable(HttpClient.getService().getWeight(familyId == null ? "" : familyId)
                .compose(new RxSchedulerTransformer<>())
                .subscribeWith(new BaseSubscriber<WeightRes>(AppConstans.WEIGHT) {
                }));
    }

    public void getWeightTrends(String familyId) {
        addDisposable(HttpClient.getService().getWeightTrends(familyId == null ? "" : familyId)
                .compose(new RxSchedulerTransformer<>())
                .subscribeWith(new BaseSubscriber<WeightTrendsRes>(AppConstans.WEIGHTTREND) {
                }));
    }

    public void members(UserInfoRes.DataBean ud, String memberid) {
        addDisposable(HttpClient.getService().members()
                .compose(new RxSchedulerTransformer<>())
                .subscribeWith(new DisposableSubscriber<MembersRes>() {
                    @Override
                    public void onNext(MembersRes membersRes) {
                        MyApplication.membersData.clear();
                        MembersRes.DataBean md = new MembersRes.DataBean();
                        md.setAvatar(ud.getAvatar());
                        md.setBirthday(ud.getBirthDay());
                        md.setHeight(ud.getHeight());
                        md.setMemberId("");
                        md.setWeight(ud.getWeight());
                        md.setUserId(ud.getUserId());
                        md.setSex(ud.getSex());
                        md.setRelation(0);
                        MyApplication.membersData.add(md);
                        if (membersRes.getData() != null && membersRes.getData().size() > 0)
                            MyApplication.membersData.addAll(membersRes.getData());
                        MyApplication.membersData.add(new MembersRes.DataBean());
                        getWeight(memberid);
                    }

                    @Override
                    public void onError(Throwable t) {

                    }

                    @Override
                    public void onComplete() {

                    }
                }));
    }

    public void update() {
        JsonObject mParam = new JsonObject();
        mParam.addProperty("platformType", "1");
        RequestBody rb = RequestBody.create(MediaType.parse("application/json;charset=UTF-8"), mParam.toString());
        addDisposable(HttpClient.getService().getLatestVersion(rb)
                .compose(new RxSchedulerTransformer<>())
                .subscribeWith(new BaseSubscriber<UpdateRes>(AppConstans.UPGRADE) {
                }));
    }

    public void registration(String registrationId) {
        JsonObject mParam = new JsonObject();
        mParam.addProperty("platformType", "1");
        mParam.addProperty("registrationId", registrationId);
        RequestBody rb = RequestBody.create(MediaType.parse("application/json;charset=UTF-8"), mParam.toString());
        addDisposable(HttpClient.getService().registration(rb)
                .compose(new RxSchedulerTransformer<>())
                .subscribeWith(new BaseSubscriber<EmptyRes>(0) {
                }));
    }

    public void download(UpdateRes updateInfo) {
        Disposable disposable = HttpClient.getService().downloadapk(updateInfo.getData().getVersionUrl())
                .subscribeOn(Schedulers.io())
                .observeOn(Schedulers.io())
                .subscribeWith(new DisposableObserver<ResponseBody>() {
                    @Override
                    public void onNext(ResponseBody responseBody) {
                        if (FileUtils.writeResponseBodyToDisk(responseBody, AppConstans.UPDATE_PATH)) {
                            LiveEventBus.get().with(AppConstans.DOWNLOAD_APK).post(updateInfo);
                        }
                    }

                    @Override
                    public void onError(Throwable t) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
        addDisposable(disposable);
    }

    public void getUserInfo() {
        addDisposable(HttpClient.getService().deviceList(1, 100)
                .flatMap(new Function<DeviceListRes, Publisher<UserInfoRes>>() {
                    @Override
                    public Publisher<UserInfoRes> apply(DeviceListRes deviceListRes) throws Exception {
                        if (deviceListRes.getData().getList().size() == 0)
                            SPUtils.putString(AppConstans.DEVICES, "");
                        else
                            SPUtils.putString(AppConstans.DEVICES, new Gson().toJson(deviceListRes.getData().getList(), new TypeToken<List<DeviceListRes.DataBean.ListBean>>() {
                            }.getType()));
                        return HttpClient.getService().getUserInfo();
                    }
                })
                .compose(new RxSchedulerTransformer<>())
                .subscribeWith(new BaseSubscriber<UserInfoRes>(AppConstans.INFO) {
                }));
    }
}
